const axios = require('axios')
const config = require('../config/env')

let options = {
  baseURL: config.serverApiUrl.url,
  timeout: 6000
}
if (config.serverApiUrl.host) {
  options.headers = { Host: config.serverApiUrl.host }
}

let instance = axios.create(options)

// 获取缓存路径key（规则：（1）/a/b → /a/b/；（2）a.html及本身带斜杠的这种路径不变；）
function getSeoPath(url) {
  if (typeof url !== 'string') return ''
  if (!url) return ''
  // 去掉http://或者https://
  url = url.replace(/(http|https)\:/g, '').replace(/\/\//g, '')
  let splitUrlArr = url.split('/')
  splitUrlArr.shift()
  splitUrlArr.unshift('')
  url = splitUrlArr.join('/')
  url = url.split('?')[0]
  // 去掉.html
  if (/\.[a-zA-Z0-9]+$/.test(url)) return url
  // 去掉末尾的斜杠
  if (/\/$/.test(url)) return url

  return url + '/'
}
/* 更新全局的共有数据*/
async function updateGlobalData() {
  let lastTime = parseInt(Date.now() / 1000)

  //Bug：process.professionData必须设置成不变，否则会引起路由前端后端不匹配
  if (process.professionData) {
    return
  }

  let areaList = []
  let navList = []
  let professionList = []
  try {
    let [
      {
        data: { data: areaListRes = [] }
      },
      {
        data: { data: navListRes = [] }
      },
      {
        data: { data: professionListRes = [] }
      }
    ] = await Promise.all([
      instance.get('/webapi/api/area', { params: { t: Date.now() } }),
      instance.get('/webapi/api/nav', { params: { t: Date.now() } }),
      instance.get('/webapi/api/show_profession', { params: { t: Date.now() } })
    ])
    areaList = areaListRes
    navList = navListRes
    professionList = professionListRes
  } catch (e) {}

  //必须保证process.professionData的数据完整性
  if (!process.professionData) {
    if (!areaList.length || !navList.length || !professionList.length) {
      throw new Error('Internal Error,please retry')
    }
  }

  navList.unshift({ id: '0', nav_name: '全部', path: 'all', parent_id: '0' })

  process.professionData = { areaList: areaList, navList: navList, professionList: professionList }
}

/* 更新全局的共有数据，不支持带？参数的SEO*/
async function setUrlPathSEO() {
  let lastTime = parseInt(Date.now() / 1000)
  // 缓存时间正式环境1小时，非正式环境5秒
  const cacheTime = config.environment === 'isProd' ? 60 * 60 : 5
  if (process.seoConfiMap && lastTime - process.lastSeoConfigTime < cacheTime) {
    return true
  }

  let seoConfigList = []
  let seoConfiMap = {}
  try {
    let [
      {
        data: { data: seoConfigListRes = [] }
      }
    ] = await Promise.all([instance.get('/newsapi/web/seo_config', { params: { t: Date.now() } })])

    seoConfigList = seoConfigListRes
  } catch (e) {}

  if (!seoConfigList.length) {
    return true
  }

  seoConfigList.forEach(element => {

    let path = getSeoPath(element.url)
    
    if (path) {
      seoConfiMap[path] = element
    }
  })

  process.seoConfiMap = seoConfiMap

  process.lastSeoConfigTime = lastTime

  return false
}

module.exports = async (req, res, next) => {
  let urlPath = req.url
  urlPath = getSeoPath(urlPath)
  //设置全局的页面共用参数
  try {
    await updateGlobalData()
  } catch (error) {
    return res.status(502).end('Internal Error,please retry')
  }

  //是否使用缓存SEO
  let isUserCacheSeo = await setUrlPathSEO(urlPath)
  //设置request的seo参数
  if (process.seoConfiMap && process.seoConfiMap[urlPath]) {
    req.seoConfig = process.seoConfiMap[urlPath]
    req.seoConfig.isUserCacheSeo = isUserCacheSeo ? 2 : 1
  }

  next()
}
